package com.gmrz.uap.uasconfig;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cache.CacheStoreService;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.jfinal.interceptor.SuperAdminAuthInterceptor;
import com.gmrz.uap.model.UasConfig;
import com.gmrz.uap.resource.ResourceInterceptor;
import com.gmrz.uap.util.Identities;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class UasConfigController extends ControllerSupport {

    /**
     * 主页面引导
     */
    @Before(SuperAdminAuthInterceptor.class)
    public void index() {

    }

    /**
     * 根据前台发过来的参数进行分页,查询
     */
    public void list() {

        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, SystemConst.DEFAULT_ORDERBY_CREATETS);
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        UasConfig uasConfig = getModel(UasConfig.class);

        Page<UasConfig> pages = UasConfigService.me.findListPaginate(uasConfig, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, pages.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, pages.getList());

        render(responseJsonRender(result));
    }


    public void add() {
        render("form" + SystemConst.VIEW_EXTENDSION);
    }


    public void save() {

        UasConfig uasConfig = getModel(UasConfig.class);

        if (null == uasConfig) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }


        uasConfig.setConfigId(Identities.uuid2());
        uasConfig.setUpdatets(new Timestamp(new DateTime().getMillis()));
        flag = uasConfig.save();

        if (flag) {
            message = getRes().get("system.validator.add.success");
        } else {
            message = getRes().get("system.validator.add.cache.failure");
        }


        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    public void edit() {
        setAttr("uasConfig", UasConfig.dao.findById(getPara()));
        render("form" + SystemConst.VIEW_EXTENDSION);
    }


    public void datagridUpdate() {
        UasConfig uasConfig = getModel(UasConfig.class);

        if (null == uasConfig) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }

        uasConfig.setUpdatets(new Timestamp(new DateTime().getMillis()));
        flag = uasConfig.update();

        if (flag) {
            message = "编辑配置成功！";
            AmmsCacheUtil.deleteIfSuccess(uasConfig.getConfigEname(),message);

        } else {
            message = getRes().get("system.validator.add.cache.failure");
        }


        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));

    }


    @Before(Tx.class)
    public void remove() {

        String ids = getPara(0);

        if (StrKit.isBlank(ids)) {
            message = getRes().get("system.validator.paramnull");
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
            render(responseJsonRender(result));
            return;
        }

        String[] isArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);


        for (String id : isArr) {
            flag = UasConfig.dao.deleteById(id);
            if (!flag) break;
        }

        if (flag) {
            message = getRes().get("system.validator.remove.success");
        } else {
            message = getRes().get("system.validator.remove.error");
        }

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * redis配置主页面
     */
    @Before(ResourceInterceptor.class)
    public void redis() {
        List<UasConfig> sysList = UasConfigService.me.getUserDefinedList(2);
        setAttr("sysList", sysList);
        setAttr("configType", 2);
        render("sys" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 系统配置主页面
     */
    @Before(ResourceInterceptor.class)
    public void sys() {
        List<UasConfig> sysList = UasConfigService.me.getUserDefinedList(1);
        setAttr("sysList", sysList);
        setAttr("configType", 1);
    }

    /**
     * 系统配置恢复默认
     */
    public void sysBack() {
        int configType = getParaToInt("configType", 1);

        int i = UasConfigService.me.sysBack2Default(configType, getCookie(SystemConst.COOKIE_TENANT_ID));

        if (i > 0) {
            message = getRes().get("facet.form.restore.sys.success");
        } else {
            message = getRes().get("facet.form.restore.sys.failure");
        }

        render(responseJsonRender(message));
    }

    /**
     * 用户可定义系统配置列表
     */
    public void sysConfigList() {
        UasConfigService.me.getUserDefinedList(1);
    }

    /**
     * 用户可定义redis配置列表
     */
    public void redisConfigList() {
        UasConfigService.me.getUserDefinedList(2);
    }

    /**
     * 根据id更新配置
     */
    public void update() {

        UasConfig uasConfig = getModel(UasConfig.class);

        if (UasConfigService.me.updateSysCongfig(uasConfig, getCookie(SystemConst.COOKIE_TENANT_ID))) flag = true;
        else flag = false;
        String[] configs = {"uaf.reg.status","uaf.auth.status","uaf.log.retention.days",
                "uaf.authenticator.overdue.days","uaf.vendor.accept","uaf.tenant.share","uaf.fido.log.switch"};
        List<String> configList = Arrays.asList(configs);
        if (flag) {
            message = getRes().get("facet.form.config.success");
            if(configList.contains(uasConfig.getConfigEname())){
                message = "配置修改成功";
            }
            message = AmmsCacheUtil.deleteIfSuccess(uasConfig.getConfigEname(), message);
        } else {
            message = getRes().get("facet.form.config.failure");
        }

        render(responseJsonRender(message));
    }


    /**
     * 根据属性键值更新默认值
     */
    public void setDefValByK() {
        String keyParam = getPara("keyParam");
        String valueParam = getPara("valueParam");

        if (StringUtils.isNotBlank(keyParam) && StringUtils.isNotBlank(valueParam)) {
            String[] keyArr = keyParam.split(",");
            String[] valueArr = valueParam.split(",");

            List<UasConfig> uasConfigs = new ArrayList<UasConfig>();
            UasConfig uasConfig = null;

            for (int i = 0; i < keyArr.length; i++) {
                uasConfig = new UasConfig();
                uasConfig.setConfigEname(keyArr[i]);
                uasConfig.setConfigDefaultValue(valueArr[i]);
                uasConfigs.add(uasConfig);
            }

            flag = UasConfigService.me.editDefaultValueByKey("default", uasConfigs);
        }

        if (flag) {
            message = getRes().get("facet.form.config.success");
        } else {
            message = getRes().get("facet.form.config.failure");
        }

        render(responseJsonRender(message));
    }
}
